package wn.lizzy.essay.controller;

import java.util.concurrent.Callable;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import wn.lizzy.essay.config.CustomAuthenticationProvider;
import wn.lizzy.essay.entity.User;

@Controller
@RequestMapping("/essay")
public class LoginController {
	private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public Callable<String> login(Model model, HttpSession session) {
		return () -> {
			logger.trace("/essay/login");
			AuthenticationException obj = (AuthenticationException) session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
			
			if(obj != null)
				model.addAttribute("error", obj.getMessage());
			
			return "essay/login";
		};
	}
	
	@RequestMapping({"/","/index"})
	public Callable<String> essay_index(HttpSession session, Model model){
		return () -> {
			logger.trace("index");
			User user = CustomAuthenticationProvider.getUserInfo();
			model.addAttribute("user", user);
			return "essay/index";
		};
    }
	
	@RequestMapping("/logout")
	public Callable<String> logout(HttpSession session) {
		return () -> {
			logger.trace("logout");
			session.invalidate();
			return "redirect:/essay/index";
		};
	}
}
